package com.poet.df.service;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

@Service
public class DatabaseMetaDataService {

	private static Logger logger = Logger
			.getLogger(DatabaseMetaDataService.class);

	@Resource
	private DataSource dataSource;

	private Object monitor = new Object();
	
	private volatile boolean isRereshing = false;

	/**
	 * 存储表明的缓存
	 */
	private List<Table> tableNameCache = new ArrayList<Table>();

	public List<Table> getTables() {

		if (tableNameCache.size() != 0) { // 认为数据库中的表不可能一个都没有
			return tableNameCache;
		}

		synchronized (this.monitor) {
			try {
				Connection conn = dataSource.getConnection();
				DatabaseMetaData metaData = conn.getMetaData();
				ResultSet rs = metaData.getTables(conn.getCatalog(),
						null, null, new String[] { "TABLE" });

				while (rs.next()) {
					String tableName = rs.getString("TABLE_NAME");
					String remarks = rs.getString("REMARKS");
					remarks = remarks == null ? "" : remarks;
					
//					if (!this.tableNameCache.contains(tableName)) {
						this.tableNameCache.add(new Table(tableName, remarks));
						logger.info("added table  '" + tableName
								+ "' to tableNameCache!");
//					}
				}
				try {
					conn.close();
				} catch (Exception e) {
					e.printStackTrace();
				}

				try {
					rs.close();
				} catch (Exception e) {
					e.printStackTrace();
				}

			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		return this.tableNameCache;
	}

	/**
	 * 刷新缓存
	 * 注意：暂未考虑并发问题
	 */
	public void refreshCache(){
		this.tableNameCache.clear();
		this.getTables();
	}
	
	
	
	public static class Table {
		
		private String name;
		private String remarks;
		
		public Table(){}
		
		public Table(String name,String remarks){
			this.name = name;
			this.remarks = remarks;
		}
		
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public String getRemarks() {
			return remarks;
		}
		public void setRemarks(String remarks) {
			this.remarks = remarks;
		}
		
		public String toString(){
			return name+" - " + remarks;
		}
		
	}
	
}
